import { View, Text, StyleSheet, Animated, Dimensions } from 'react-native';
import React, { useRef } from 'react';

interface MyTabsProps<T> {
  tabs: T[];
  activeTab: number;
  onPress: (item: number) => void;
}

// 获取屏幕视口的高度
const { width } = Dimensions.get('window');

const MyTabs = <T,>({ tabs, activeTab, onPress }: MyTabsProps<T>) => {
  // 滑块
  const slideBlock = useRef(
    new Animated.Value(
      (width / tabs.length) * activeTab + width / tabs.length / 2 - 5,
    ),
  ).current;

  const changeActiveTab = (index: number) => {
    onPress(index);
    Animated.timing(slideBlock, {
      toValue: (width / tabs.length) * index + width / tabs.length / 2 - 5,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };

  return (
    <View style={styles.container}>
      {tabs.map((item, index) => {
        return (
          <Text
            key={index}
            onPress={() => {
              changeActiveTab(index);
            }}
            style={[
              activeTab === index ? styles.activeTab : {},
              { width: width / tabs.length, textAlign: 'center' },
            ]}
          >
            {item + ''}
          </Text>
        );
      })}
      <Animated.View
        style={[styles.slideBlock, { transform: [{ translateX: slideBlock }] }]}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    height: 40,
    position: 'relative',

    justifyContent: 'space-around',
    flexDirection: 'row',
    paddingTop: 10,
    paddingBottom: 10,
  },
  activeTab: {
    color: 'red',
  },
  slideBlock: {
    position: 'absolute',
    left: 0,
    bottom: 0,
    height: 5,
    width: 10,
    backgroundColor: 'red',
  },
});

export default MyTabs;
